package com.synergy.stockflow.service;

import com.synergy.stockflow.model.JwtProperties;
import com.synergy.stockflow.utils.JwtUtils;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Optional;

/**
 * 封装符合Spring Boot配置
 */
@Getter
@Service
public class JwtService {

    @Autowired
    public JwtProperties jwtProperties;

    // 生成普通 token（登录态）
    public String generateToken(String username) {
        return JwtUtils.generateToken(username, jwtProperties.getSecret(), jwtProperties.getExpiration());
    }

    // 生成记住我 token
    public String generateRememberMeToken(String username) {
        return JwtUtils.generateToken(username, jwtProperties.getSecret(), jwtProperties.getRemember());
    }

    // 根据 rememberMe 选择过期时间
    public String generateToken(String username, boolean rememberMe) {
        long expiration = rememberMe ? jwtProperties.getRemember() : jwtProperties.getExpiration();
        return JwtUtils.generateToken(username, jwtProperties.getSecret(), expiration);
    }
    /**
     * 从 HttpServletRequest 中提取 JWT token
     */
    public String extractToken(HttpServletRequest request){
        String bearerToken = request.getHeader(jwtProperties.getHeader().trim());
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(jwtProperties.getPrefix())) {
            return bearerToken.substring(jwtProperties.getPrefix().length() + 1);
        }
        return null;
    }
    /**
     * 提取用户名（subject）
     */
    public String extractSubject(String token) {
        return JwtUtils.extractSubject(token, jwtProperties.getSecret());
    }

    /**
     * 提取自定义声明
     */
    public Object extractClaim(String token, String key) {
        return JwtUtils.extractClaim(token, jwtProperties.getSecret(), key);
    }
    /**
     * 添加前缀（如 Bearer）
     */
    public String withPrefix(String token) {
        return jwtProperties.getPrefix().trim() + " " + token;
    }

    public long getExpiration(String token) {
        try {
            return JwtUtils.getExpiration(token, jwtProperties.getSecret());
        } catch (Exception e) {
            throw new RuntimeException("Invalid token", e);
        }
    }

    /**
     * 判断 token 是否已过期（包含异常情况视为过期）
     */
    public boolean isExpired(String token){
        return JwtUtils.isExpired(token, jwtProperties.getSecret());
    }


    /**
     * 验证 token 是否有效
     */
    public boolean validateToken(String token) {
        return StringUtils.hasText(token) && !isExpired(token);
    }
}
